from sakucrm import models
from stack.service.stack import StackConfig
from stack.service.stack import get_choice_text
from stack.service.stack import Option
from django import forms
from django.shortcuts import HttpResponse
from django.conf import settings
from django.db import transaction
from django.urls import reverse
from django.utils.safestring import mark_safe

class CourseRecordConfig(StackConfig):
    '''
    上课记录
    '''
    def display_title(self,row=None,header=False):
        if header:
            return '上课记录'

        # tpl='{} {} day {}'.format(row.class_obj.course.name,row.class_obj.semester,row.day_num)
        # return tpl
        url = reverse('stack:sakucrm_studyrecord_list')
        return mark_safe('<a href="{}?ccid={}">{} {} day {}</a>'.format(url, row.pk,row.class_obj.course.name,row.class_obj.semester,row.day_num))
    list_display = [display_title,]

    def get_list_display(self):
        val=super().get_list_display()
        val.insert(0,StackConfig.display_checkbox)
        return val

    def muti_init(self,request):
        '''
        批量初始化话  学生学习记录表
        :param request:
        :return:
        '''
        id_list=request.POST.getlist('pk')
        #找到选中上课记录的班级
        #找到班级中的每个学生
        #为每个学生生成一条学习记录
        for nid in id_list:
            record_obj=models.CourseRecord.objects.get(id=nid)  #找到上课记录 对象
            stu_list=models.Student.objects.filter(class_list=record_obj.class_obj)  #根据上课记录中的 班级对象 找到学生列表
            #判断 是否存在 学习记录
            exists=models.StudyRecord.objects.filter(course_record=record_obj).exists()
            if exists:
                continue
            study_record_list=[]   #存储每个学生记录的对象   进行批量创建
            for stu_obj in stu_list:
                study_record_list.append(models.StudyRecord(course_record=record_obj,student=stu_obj))
            models.StudyRecord.objects.bulk_create(study_record_list)
    muti_init.text = '批量初始化'
    action_list = [muti_init,]